package com.example.hlddz2.ui.activity;

import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.hlddz2.R;
import com.example.hlddz2.model.ProductDetailResponse;
import com.example.hlddz2.network.ApiService;
import com.example.hlddz2.repository.ProductRepository;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.observers.DisposableObserver;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ProductDetailActivity extends AppCompatActivity {

    public static final String EXTRA_GOODS_ID = "extra_goods_id";

    private TextView tvName;
    private TextView tvPrice;
    private android.webkit.WebView webIntro;
    private RecyclerView rvImages;
    private ImagesAdapter imagesAdapter;
    private android.widget.Button btnAddCart;

    private ProductRepository repository;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_detail);

        tvName = findViewById(R.id.tv_name);
        tvPrice = findViewById(R.id.tv_price);
        webIntro = findViewById(R.id.web_intro);
        rvImages = findViewById(R.id.rv_images);
        btnAddCart = findViewById(R.id.btn_add_cart);
        rvImages.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        imagesAdapter = new ImagesAdapter();
        rvImages.setAdapter(imagesAdapter);

        // Retrofit
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(logging).build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api-hmugo-web.itheima.net/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        ApiService api = retrofit.create(ApiService.class);
        repository = new ProductRepository(api);

        int goodsId = getIntent().getIntExtra(EXTRA_GOODS_ID, 0);
        if (goodsId != 0) {
            loadDetail(goodsId);
        }

        btnAddCart.setOnClickListener(v -> {
            Object tag = v.getTag();
            if (tag instanceof ProductDetailResponse.ProductDetail) {
                ProductDetailResponse.ProductDetail d = (ProductDetailResponse.ProductDetail) tag;
                com.example.hlddz2.repository.CartRepository.CartItem item = new com.example.hlddz2.repository.CartRepository.CartItem();
                item.goodsId = d.getGoods_id();
                item.name = d.getGoods_name();
                item.price = d.getGoods_price();
                item.image = (d.getPics() != null && !d.getPics().isEmpty()) ? d.getPics().get(0).getPics_big() : "";
                item.count = 1;
                com.example.hlddz2.repository.CartRepository.getInstance(this).add(item);
                android.widget.Toast.makeText(this, "已加入购物车", android.widget.Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void loadDetail(int goodsId) {
        repository.getGoodsDetail(goodsId).subscribe(new DisposableObserver<ProductDetailResponse.ProductDetail>() {
            @Override
            public void onNext(ProductDetailResponse.ProductDetail d) {
                tvName.setText(d.getGoods_name());
                tvPrice.setText("¥ " + d.getGoods_price());
                // Render HTML in WebView with simple CSS for images
                android.webkit.WebSettings settings = webIntro.getSettings();
                settings.setJavaScriptEnabled(false);
                settings.setDomStorageEnabled(true);
                settings.setLoadWithOverviewMode(true);
                settings.setUseWideViewPort(true);
                String css = "<style>img{max-width:100%;height:auto;} body{color:#222;font-size:14px;line-height:1.6;padding:0;margin:0;}</style>";
                String html = "<html><head>" + css + "</head><body>" + (d.getGoods_introduce() == null ? "" : d.getGoods_introduce()) + "</body></html>";
                webIntro.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
                btnAddCart.setTag(d);
                List<String> urls = new ArrayList<>();
                if (d.getPics() != null) {
                    for (ProductDetailResponse.Pic p : d.getPics()) {
                        if (p.getPics_big() != null && !p.getPics_big().isEmpty()) {
                            urls.add(p.getPics_big());
                        }
                    }
                }
                imagesAdapter.setData(urls);
            }

            @Override
            public void onError(Throwable e) { }

            @Override
            public void onComplete() { }
        });
    }

    static class ImagesAdapter extends RecyclerView.Adapter<ImagesAdapter.VH> {
        private List<String> data = new ArrayList<>();
        void setData(List<String> d) { data = d; notifyDataSetChanged(); }

        @Override
        public VH onCreateViewHolder(android.view.ViewGroup parent, int viewType) {
            android.view.View v = android.view.LayoutInflater.from(parent.getContext()).inflate(R.layout.item_detail_image, parent, false);
            return new VH(v);
        }

        @Override
        public void onBindViewHolder(VH holder, int position) {
            String url = data.get(position);
            Glide.with(holder.itemView.getContext())
                    .load(url)
                    .placeholder(R.color.light_gray)
                    .into(holder.iv);
        }

        @Override
        public int getItemCount() { return data == null ? 0 : data.size(); }

        static class VH extends RecyclerView.ViewHolder {
            ImageView iv;
            VH(android.view.View itemView) {
                super(itemView);
                iv = itemView.findViewById(R.id.iv_image);
            }
        }
    }
}


